#region (c) 2009 Rinat Abdullin

// Copyright (c) Rinat Abdullin
// All Rights Reserved
// Site: http://abdullin.com

#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Jayrock.Json;
using Jayrock.Json.Conversion;
using Jayrock.Json.Conversion.Converters;

namespace NCouch.Json
{
	sealed class FirstConstructorImporter : ImporterBase
	{
		readonly ConstructorInfo _constructor;
		readonly ParameterInfo[] _parameters;
		readonly Dictionary<string, int> _dictionary;


		public FirstConstructorImporter(Type type)
			: base(type)
		{
			_constructor = type.GetConstructors()[0];
			_parameters = _constructor.GetParameters();
			_dictionary = _parameters.Select((p, i) => new
			{
				p.Name,
				i
			}).ToDictionary(x => x.Name, x => x.i,
				StringComparer.InvariantCultureIgnoreCase);
		}

		protected override object ImportFromObject(ImportContext context, JsonReader reader)
		{
			reader.Read();
			var objects = new object[_parameters.Length];
			while (reader.TokenClass != JsonTokenClass.EndObject)
			{
				string memberName = reader.ReadMember();

				int index;
				if (_dictionary.TryGetValue(memberName, out index))
				{
					objects[index] = context.Import(_parameters[index].ParameterType, reader);
				}
				else
				{
					reader.Skip();
				}
			}
			reader.Read();
			return Activator.CreateInstance(OutputType, objects);
		}
	}
}